package com.doris.media.picker.utils.permission

import android.app.Activity
import android.content.res.Configuration
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.PopupWindow
import android.widget.TextView
import com.doris.media.picker.R
import com.hjq.permissions.*
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import org.jetbrains.anko.toast

class PermissionInterceptor(
    private var mTitle: String,
    private val mContent: String,
) : OnPermissionInterceptor {

    private val mHandler = Handler(Looper.getMainLooper())

    // 权限申请标记
    private var mRequestFlag = false

    // 权限申请说明 Popup
    private lateinit var mPermissionPopup: PopupWindow

    override fun launchPermissionRequest(
        activity: Activity,
        allPermissions: MutableList<String>,
        callback: OnPermissionCallback?,
    ) {
        mRequestFlag = true
        val deniedPermissions = XXPermissions.getDenied(activity, allPermissions)
//        val decorView = activity.window.decorView as ViewGroup
        val activityOrientation = activity.resources.configuration.orientation
        mTitle = PermissionNameConvert.getPermissionString(deniedPermissions.toMutableList())
        var showPopupWindow = activityOrientation == Configuration.ORIENTATION_PORTRAIT
        val listSpecialPermission = arrayListOf<String>()
        val listCommonPermission = arrayListOf<String>()
        run loop@{
            allPermissions.forEach { permission ->
                if (XXPermissions.isSpecial(permission) || isManagerExternalStorage(permission)) {
                    listSpecialPermission.add(permission)
                } else {
                    listCommonPermission.add(permission)
                }
                if (!XXPermissions.isSpecial(permission)) {
                    return@forEach
                }
                if (XXPermissions.isGranted(activity, permission)) {
                    return@forEach
                }
                if (isManagerExternalStorage(permission)) {
                    return@forEach
                }
                // 如果申请的权限带有特殊权限，并且还没有授予的话
                // 就不用 PopupWindow 对话框来显示，而是用 Dialog 来显示
                showPopupWindow = false
                return@loop
            }
        }
        if (showPopupWindow) {
            launchPermissionAndShowPop(activity, ArrayList(deniedPermissions), callback ,mRequestFlag)
        } else {
            if (listSpecialPermission.isNotEmpty()) {
                QMUIDialog.MessageDialogBuilder(activity).setCancelable(false).setCanceledOnTouchOutside(false)
                    .setTitle(mTitle).setMessage(mContent)
                    .addAction("取消") { dialog, _ ->
                        dialog.dismiss()
                        callback?.onDenied(listSpecialPermission, false)
                    }.addAction("前往授权") { dialog, _ ->
                        dialog.dismiss()
                        PermissionFragment.launch(activity, listSpecialPermission, this, object : OnPermissionCallback {
                            override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                                if (allGranted && listCommonPermission.isNotEmpty()) {
                                    launchPermissionAndShowPop(activity, listCommonPermission, callback)
                                } else
                                    callback?.onGranted(permissions, allGranted)
                            }

                            override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                                callback?.onDenied(permissions, doNotAskAgain)
                            }
                        })
                    }.show()
            }
        }
    }

    private fun launchPermissionAndShowPop(
        activity: Activity,
        listPermission: ArrayList<String>,
        callback: OnPermissionCallback?,
        requestFlag :Boolean = true
    ) {
        PermissionFragment.launch(
            activity,
            listPermission,
            this@PermissionInterceptor,
            callback
        )
        // 延迟 300 毫秒是为了避免出现 PopupWindow 显示然后立马消失的情况
        // 因为框架没有办法在还没有申请权限的情况下，去判断权限是否永久拒绝了，必须要在发起权限申请之后
        // 所以只能通过延迟显示 PopupWindow 来做这件事，如果 300 毫秒内权限申请没有结束，证明本次申请的权限没有永久拒绝
        mHandler.postDelayed({
            if (!requestFlag) return@postDelayed
            if (activity.isFinishing || activity.isDestroyed) return@postDelayed
            val decorView = activity.window.decorView as ViewGroup
            showPopupWindow(activity, decorView)
        }, 300)
    }

    private fun isManagerExternalStorage(permission: String): Boolean {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.R && TextUtils.equals(Permission.MANAGE_EXTERNAL_STORAGE, permission)
    }

    override fun grantedPermissionRequest(
        activity: Activity,
        allPermissions: MutableList<String>,
        grantedPermissions: MutableList<String>,
        allGranted: Boolean,
        callback: OnPermissionCallback?,
    ) {
        if (callback == null) return
        callback.onGranted(grantedPermissions, allGranted)
    }

    override fun deniedPermissionRequest(
        activity: Activity,
        allPermissions: MutableList<String>,
        deniedPermissions: MutableList<String>,
        doNotAskAgain: Boolean,
        callback: OnPermissionCallback?,
    ) {
        callback?.onDenied(deniedPermissions, doNotAskAgain)

        if (doNotAskAgain) {
            mTitle = PermissionNameConvert.getPermissionString(deniedPermissions.toMutableList())
            showPermissionSettingDialog(activity, allPermissions, deniedPermissions, callback)
            return
        }
        activity.toast("未授予权限，会导致功能无法使用")
    }

    override fun finishPermissionRequest(
        activity: Activity,
        allPermissions: MutableList<String>,
        skipRequest: Boolean,
        callback: OnPermissionCallback?,
    ) {
        mRequestFlag = false
        dismissPopupWindow()
    }

    private fun showPopupWindow(activity: Activity, decorView: ViewGroup) {
        if (!this::mPermissionPopup.isInitialized) {
            val contentView = LayoutInflater.from(activity)
                .inflate(R.layout.media_picker_popup_permission_description, decorView, false)
            mPermissionPopup = PopupWindow(activity)
            mPermissionPopup.contentView = contentView
            mPermissionPopup.width = WindowManager.LayoutParams.MATCH_PARENT
            mPermissionPopup.height = WindowManager.LayoutParams.WRAP_CONTENT
            mPermissionPopup.animationStyle = android.R.style.Animation_Dialog
            mPermissionPopup.isTouchable = true
            mPermissionPopup.isOutsideTouchable = true
            mPermissionPopup.setBackgroundDrawable(ColorDrawable(0x00000000))
        }
        mPermissionPopup.contentView.findViewById<TextView>(R.id.mediaPicker_permission_title)
            .text = mTitle
        mPermissionPopup.contentView.findViewById<TextView>(R.id.mediaPicker_permission_content)
            .text = mContent
        mPermissionPopup.showAtLocation(decorView, Gravity.TOP, 0, 0)
    }

    private fun dismissPopupWindow() {
        if (!this::mPermissionPopup.isInitialized) return
        if (!mPermissionPopup.isShowing) return
        mPermissionPopup.dismiss()
    }

    private fun showPermissionSettingDialog(
        activity: Activity?,
        allPermissions: MutableList<String>,
        deniedPermissions: MutableList<String>,
        callback: OnPermissionCallback?,
    ) {
        if (activity == null || activity.isFinishing || activity.isDestroyed) {
            return
        }
        QMUIDialog.MessageDialogBuilder(activity).setCancelable(false).setCanceledOnTouchOutside(false)
            .setTitle(mTitle).setMessage("获取失败或被禁止，请手动授予权限。\n\n${mContent}")
            .addAction("取消") { dialog, _ ->
                dismissPopupWindow()
                dialog.dismiss()
            }
            .addAction("前往授权") { dialog, _ ->
                dialog.dismiss()
                XXPermissions.startPermissionActivity(
                    activity, deniedPermissions, object : OnPermissionPageCallback {
                        override fun onGranted() {
                            dismissPopupWindow()
                            callback?.onGranted(allPermissions, true)
                        }

                        override fun onDenied() {
                            val deniedList = XXPermissions.getDenied(activity, allPermissions)
                            mTitle = PermissionNameConvert.getPermissionString(deniedList)
                            showPermissionSettingDialog(
                                activity, allPermissions,
                                deniedList, callback
                            )
                        }
                    })
            }.show()
    }
}